﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Device.Location;

namespace WeatherFrame
{
    public class LocationService
    {
        public static LocationService Instance = new LocationService();

        private LocationService()
        {
        }

        GeoCoordinateWatcher watcher;
        Location loc;
        int noDataCount = 0;

        internal void FindCoordinates(Location location)
        {
            loc = location;
            if (watcher == null)
            {
                watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default) { MovementThreshold = 20 };
                watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
            }
            noDataCount = 0;
            watcher.Start();
        }

        void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            if (e.Status == GeoPositionStatus.Initializing) return;
            if (e.Status == GeoPositionStatus.Ready)
            {
                watcher.Stop();
                loc.IsWaitingForWeather = false;
                var pos = watcher.Position.Location;
                loc.Latitude = pos.Latitude;
                loc.Longitude = pos.Longitude;
                App.ViewModel.service.GetWeatherForecastAsync(loc);
            }
            if (e.Status == GeoPositionStatus.Disabled)
            {
                watcher.Stop();
                loc.IsWaitingForWeather = false;
                loc.SetError("Cannot determine your location." + Environment.NewLine + "Location service not available."); 
            }
            if (e.Status == GeoPositionStatus.NoData)
            {
                noDataCount++;
                if (noDataCount >= 5)
                {
                    watcher.Stop();
                    loc.IsWaitingForWeather = false;
                    loc.SetError("Cannot determine your location."); 
                }
            }
        }


    }
}
